package com.wds.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wds.common.utils.WebUtils;
import com.wds.domain.JsonResult;
import com.wds.domain.entity.Article;
import com.wds.domain.type.SystemConstants;
import com.wds.domain.vo.CategoryPageVo;
import com.wds.domain.vo.CategoryQueryAllVo;
import com.wds.domain.vo.CategoryVo;
import com.wds.exception.CustomException;
import com.wds.mapper.CategoryMapper;
import com.wds.domain.entity.Category;
import com.wds.service.ArticleService;
import com.wds.service.CategoryService;
import com.wds.common.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 分类表(Category)表服务实现类
 *
 * @author wds
 * @since 2022-10-21 15:50:18
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private ArticleService articleService;

    @Override
    public JsonResult<List<CategoryVo>> getCategoryList() {
        // 查询出所有非草稿文章
        LambdaQueryWrapper<Article> articleWrapper = new LambdaQueryWrapper<>();
        articleWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleService.list(articleWrapper);

        // 只保留ID
        Set<Long> IDList = articleList.stream()
                .map(Article::getCategoryId)
                .collect(Collectors.toSet());

        //查询对应的分类
        List<Category> categoryList = listByIds(IDList);
        //去掉禁用状态的分类
        List<Category> categories = categoryList.stream().filter(category ->
                        SystemConstants.CATEGORY_STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        //封装VO
        List<CategoryVo> categoryVos = BeanCopyUtils.copyList(categories, CategoryVo.class);
        return JsonResult.ok(categoryVos);
    }

    @Override
    public JsonResult<List<CategoryQueryAllVo>> queryAllCategory() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
//        启用状态
        queryWrapper.eq(Category::getStatus, SystemConstants.CATEGORY_STATUS_NORMAL);
        List<Category> categories = list(queryWrapper);
        List<CategoryQueryAllVo> vos = BeanCopyUtils.copyList(categories, CategoryQueryAllVo.class);
        return JsonResult.ok(vos);
    }

    @Override
    public JsonResult<CategoryPageVo> queryCategoryPage(Integer pageNum, Integer pageSize, String name, Integer status) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize > 40) {
            pageSize = 10;
        }
        Page<Category> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(status != null, Category::getStatus, status);
        queryWrapper.like(StringUtils.hasText(name), Category::getName, name);
        page(page, queryWrapper);

        CategoryPageVo pageVo = new CategoryPageVo();
        pageVo.setRows(page.getRecords());
        pageVo.setTotal(page.getTotal());
        return JsonResult.ok(pageVo);
    }

    @Override
    public JsonResult<Object> addNewCategory(Category dto) {
        if (!StringUtils.hasText(dto.getName()) || dto.getStatus() == null) {
            throw new CustomException("请检查信息是否填写完整后提交");
        }
        Category addCategory = new Category();
        addCategory.setName(dto.getName());
        addCategory.setDescription(dto.getDescription());
        addCategory.setStatus(dto.getStatus());

        save(addCategory);
        return JsonResult.ok();
    }

    @Override
    public JsonResult<Object> delete(List<Long> ids) {
        if (ids == null || ids.size() == 0) {
            throw new CustomException("删除时出错，请检查id");
        }
        removeByIds(ids);
        return JsonResult.ok();
    }

    @Override
    public JsonResult<Object> queryOne(Long id) {
        Category category = getById(id);
        return JsonResult.ok(category);
    }

    @Override
    public JsonResult<Object> updateCategory(Category category) {
        Category updateCategory = new Category();
        updateCategory.setStatus(category.getStatus());
        updateCategory.setName(category.getName());
        updateCategory.setId(category.getId());
        updateCategory.setDescription(category.getDescription());

        updateById(updateCategory);
        return JsonResult.ok();
    }

    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        try {
//          设置文件下载的响应头
            WebUtils.setDownLoadExcelHeader("分类导出.xlsx", response);
//            查询全部分类
//            生成excel
//            写到响应体
//            这里要指定类对象否则 看不到表头
            EasyExcel.write(response.getOutputStream(),Category.class).sheet("分类表").needHead(Boolean.TRUE).doWrite(list());
        } catch (UnsupportedEncodingException e) {
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.getWriter().print(new ObjectMapper().writeValueAsString(JsonResult.fail("未知错误，导出失败。")));
            log.error("export excel error: " + e.getMessage());
        }


    }
}

